//
//  ZCComposeViewController.swift
//  weibo
//
//  Created by Ning Xie on 16/8/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZCComposeViewController: UIViewController {

    
    //MARK:-懒加载控件
    //右边按钮
    private lazy var rightBarBtn:UIButton = {
       
        let rightItem = UIButton(type: UIButtonType.Custom)
        rightItem.bounds.size = CGSizeMake(40, 30)
        rightItem.setTitle("发送", forState: .Normal)
        rightItem.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        rightItem.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        rightItem.titleLabel?.font = UIFont.systemFontOfSize(14)
        rightItem.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        rightItem.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        rightItem.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        rightItem.addTarget(self, action: #selector(ZCComposeViewController.sendBtnClick), forControlEvents: .TouchUpInside)

        return rightItem
    
    }()
    //表头文字
    private lazy var titleLabel:UILabel = {
       let label = UILabel(fontSize: 15, textColor: UIColor.darkGrayColor())
        
        if let name = ZCUserInfoViewModel.sharedUserInfo.userInfo?.name{
            let result = "发微博\n\(name)"
            let range  = (result as NSString).rangeOfString(name)
            let attributedStr = NSMutableAttributedString(string: result)
            
            attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], range: range)
            label.attributedText = attributedStr
        }else{
            label.text = "发微博"
        }
        label.numberOfLines = 0
        label.sizeToFit()
        label.textAlignment = .Center
        
        return label
    }()
    //文本输入框
    private lazy var textView: ZCComposeTextView = {
       let view = ZCComposeTextView()
        view.backgroundColor = UIColor.whiteColor()
        view.delegate = self
        view.placeHolder = "分享新鲜事..."
        view.font = UIFont.systemFontOfSize(20)
        view.alwaysBounceVertical = true
//        view.bounces = false
//
        return view
    }()
    //配图
    private lazy var picView: ZCComposePicView = {
        let view = ZCComposePicView()
        view.backgroundColor = self.textView.backgroundColor
        view.addImageButtonClosure = { [weak self] in
            
            self!.didSelectedPictureButton()
        }
        view.rightButtonItemEnableClosure = { [weak self] (enabled:Bool)->() in
            
            self!.navigationItem.rightBarButtonItem?.enabled = enabled

        }
        
        return view
    }()
    //底部工具条
    private lazy var stackView :ZCComposeToolBar = {
        let view = ZCComposeToolBar(frame: CGRectZero)
        
        return view
        
    }()
    //表情键盘
    private lazy var emoticonKeyBoard:ZCEmoticonKeyBoard = {
        let view = ZCEmoticonKeyBoard()
        view.size = CGSizeMake(view.frame.size.width, 216)
        
        return view
    }()
    
    
    
    //MARK:-页面布局
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        dispatch_async(dispatch_get_main_queue()) { 
            //进入界面,调出键盘
            self.textView.becomeFirstResponder()
        }
        
    }
    
    private func setupNavUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(ZCComposeViewController.dismissComposeVC))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarBtn)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleLabel
    }
    //用于监听通知
    private func receiveNotification(){
        
        //监听键盘frame的改变,更改底部工具条的frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZCComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听点击删除按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZCComposeViewController.emoticonDeleteButtonAction), name: EmoticonDeleteButtonActionNotification, object: nil)
        //监听长按删除按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZCComposeViewController.emoticonDeleteButtonLongPress), name: EmoticonDeleteButtonLongPressNotification, object: nil)
        //监听点击表情按钮
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZCComposeViewController.didSelectedEmoticonButtonAction(_:)), name: DidSelectedEmoticonButtonActionNotification, object: nil)
        
    }

    
    private func setupUI(){
        
        setupNavUI()
        
        receiveNotification()
        
        
        //布局子控件
        view.addSubview(textView)
        textView.addSubview(picView)
        view.addSubview(stackView)
        
        //设置子控件约束
        textView.snp_makeConstraints { (make) in
            
            make.top.trailing.leading.equalTo(view)
            make.bottom.equalTo(stackView.snp_top)
        }
        picView.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        
        stackView.snp_makeConstraints { (make) in
            make.trailing.leading.bottom.equalTo(view)
            make.height.equalTo(35)
        }

        stackView.didSelectedButtonClosure = { [weak self] (type: ZCComposeToolBarButtonType)->() in
            
            switch type {
            case .Picture:
//                print("图片")
                self?.didSelectedPictureButton()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
//                print("笑脸")
                self?.didSelectedEmotionButton()
            case .Add:
                print("加号")

            }
        }
        
        
    }
    
    //监听键盘frame改变方法
    @objc private func keyboardWillChangeFrame(noti:NSNotification){
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        stackView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - self.view.bounds.size.height)
        }
        UIView.animateWithDuration(duration) { 
            self.view.layoutIfNeeded()
        }
    }
    //表情键盘点击删除按钮
    @objc private func emoticonDeleteButtonAction(){
        
        textView.deleteBackward()
    }
    //表情键盘长按删除按钮
    @objc private func emoticonDeleteButtonLongPress(){
        
        
    }
    //表情键盘点击表情按钮
    @objc private func didSelectedEmoticonButtonAction(noti:NSNotification){
        
        let button = noti.object as! ZCEmoticonButton
        let emoticon = button.emoticonModel!
        
        textView.insertEmoticon(emoticon)
    }
    
    //MARK:-发送按钮的点击事件
    @objc private func sendBtnClick(){
        
        SVProgressHUD.show()
        ProgressStyle()
        
        if picView.imageArray.count > 0
        {
            let accessToken = ZCUserInfoViewModel.sharedUserInfo.accessToken!
            var status :String?
            if textView.text != "" {
                status = textView.emoticonText
            }else{
                status = "分享图片"
            }
            let image = picView.imageArray.first!
            
            ZCNetworkTools.sharedNetworkTools.requestUpload(accessToken, status: status!, image: image, callBack: { (response, error) in
                
                
                if error != nil{
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    ProgressStyle()
                }else{
                    
                    self.dismissComposeVC()
                    SVProgressHUD.showSuccessWithStatus("发表成功")
                    ProgressStyle()
                }
            })
        }else
        {
            let accessToken = ZCUserInfoViewModel.sharedUserInfo.accessToken!
            let status = textView.emoticonText

            ZCNetworkTools.sharedNetworkTools.requestUpdate(accessToken, status: status!) { (response, error) in
                
                if error != nil{
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    SVProgressHUD.setDefaultStyle(.Dark)

                }else{
                    
                    self.dismissComposeVC()
                    SVProgressHUD.showSuccessWithStatus("发表成功")
                    SVProgressHUD.setDefaultStyle(.Dark)

                }
            }
        }
        
        
        
    }
    
    //MARK:-移除页面
    @objc private func dismissComposeVC(){
        
        dismissViewControllerAnimated(true, completion: nil)
        self.view.endEditing(true)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
   
}

extension ZCComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}


extension ZCComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //点击图片按钮方法
    func didSelectedPictureButton(){
        let pickerVC = UIImagePickerController()
        pickerVC.delegate = self
        
        
        presentViewController(pickerVC, animated: true, completion: nil)
    }
    
    func didSelectedEmotionButton(){
        
        if textView.inputView == nil {
            textView.inputView = emoticonKeyBoard
            stackView.switchEmoticonButtonImage(true)
            
        }else{
            textView.inputView = nil
            stackView.switchEmoticonButtonImage(false)
        }
        
        textView.becomeFirstResponder()
        textView.reloadInputViews()
        
    }
    func didAddButton(){
        
    }
    
    
    //UIImagePickerControllerDelegate代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        picView.addImage(image)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
